package demo.IOStream;

import java.io.*;
import java.util.Scanner;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/13-08-13-13:59
 * @Description：demo.IOStream
 */
public class filePipeStream {
    public static void main(String[] args) {
        PipedReader pr = new PipedReader();
        PipedWriter pw = new PipedWriter();
        try {
            pr.connect(pw);
            new PipeThread(pw).start();
            Thread.sleep(10);
            new PipeRead(pr).start();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class PipeThread extends Thread{
    private PipedWriter pw;

    public PipeThread(PipedWriter pw) {
        this.pw = pw;
    }

    @Override
    public void run() {
        Scanner sc = new Scanner(System.in);
        byte[] b = new byte[1024];
        try {
            String str = sc.next();
            pw.write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                pw.close();
                sc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
class PipeRead extends Thread{
    private PipedReader pr;

    public PipeRead(PipedReader pr) {
        this.pr = pr;
    }

    @Override
    public void run() {
        char[] b = new char[1024];
        int len = -1;
        File file = new File("hello.txt");
        FileWriter writer = null;
        try {
            writer = new FileWriter(file);
            while ((len = pr.read(b)) != -1){
                writer.write(b,0,len);
            }
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                writer.close();
                pr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
